#pragma once
#include <iostream>
using namespace std;

#include "protocol.hpp"

enum
{
    DIV_ZERO = 1,
    MOD_ZERO,
    Other_Oper,
};

class ServerCal
{
public:
    ServerCal() {}

    Response CalcHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;

        case '-':
            resp.result = req.x - req.y;
            break;

        case '*':
            resp.result = req.x * req.y;
            break;

        case '/':
            {
                if (req.y == 0)
                {
                    resp.code = DIV_ZERO;
                }
                else
                {
                    resp.result = req.x / req.y;
                }
            }
            break;
        case '%':
            {
                if (req.y == 0)
                {
                    resp.code = MOD_ZERO;
                }
                else
                {
                    resp.result = req.x % req.y;
                }
            }
            break;

        default:
            resp.code = Other_Oper;
            break;
        }

        return resp;
    }

    string Calculator(string &package)
    {
        string content;
        bool r1 = Decode(package, &content);
        if (!r1)
            return"";
        Request req;
        bool r2 = req.deserialize(content);
        if (!r2)
            return"";

        content = "";
        Response resp = CalcHelper(req); // req的计算结果给resp。
        resp.serialize(&content);        // 序列化， 将resp进行序列化放在content中
        content = Encode(content);       // 添加报头

        return content;
    }
};